import React, { useState, useEffect, useRef } from 'react';
import {
  Tag,
  Alert,
  Card,
  Button,
  List,
  Table,
  Popconfirm,
  DatePicker,
  Input,
  Typography,
  Tooltip,
  Avatar,
  Space,
  message,
} from 'antd';
import {
  createFromIconfontCN,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
  CopyOutlined,
  FieldTimeOutlined,
} from '@ant-design/icons';
import type { DatePickerProps, RangePickerProps } from 'antd/es/date-picker';
import { ProTable } from '@ant-design/pro-components';
import ProCard from '@ant-design/pro-card';
import AddOrEditShareUrl from '../AddOrEditShareUrl';
import { useModel, useParams } from 'umi';
import styles from './index.less';
import {
  findByVrPreviewMap,
  deleteVrPreview,
  generateVrPreview,
} from '@/services/swagger/vrPreviewController';
import moment from 'moment';

const IconFont = createFromIconfontCN({
  scriptUrl: ['/iconfont/iconfont.js'],
});

const { Paragraph, Title, Text } = Typography;

const ShareConfig: React.FC = (props: any) => {
  const { instanceData } = props;
  const shareEditRef = useRef<any>();
  const params: any = useParams();
  const actionRef = useRef<any>();
  const { instanceId } = params;
  const [endTime, setEndTime] = useState<string>('');
  const [currentId, setCurrentId] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);

  const { panoramaData } = useModel('PanoramicTool.panoramaData', (ret) => ({
    panoramaData: ret.panoramaData,
  }));

  /**
   * 复制文本到剪贴板
   */
  const handleCopy = (text) => {
    if (text) {
      const tempInput = document.createElement('input');
      tempInput.style.opacity = '0';
      tempInput.value = text;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand('copy');
      document.body.removeChild(tempInput);
      message.success('复制成功');
    }
  };

  const onChange = (
    value: DatePickerProps['value'] | RangePickerProps['value'],
    dateString: [string, string] | string,
  ) => {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
    setEndTime(dateString);
  };

  const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {};

  const produceUrl = () => {
    const params = {
      ems_vrpreview_enttime: endTime,
      ems_vrpreview_instanceid: instanceId,
      ems_vrpreview_instanceno: instanceData?.ems_instance_no,
    };
    generateVrPreview(params).then((res) => {
      if (res.code === 200) {
        message.success(res.message);
      }
      actionRef?.current?.reload();
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'ems_vrpreview_id',
      valueType: 'index',
      hideInForm: true,
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      title: '链接地址',
      key: 'ems_vrpreview_accessurl',
      dataIndex: 'ems_vrpreview_accessurl',
      render: (_, record) => {
        return (
          <Input.Group compact>
            <Input style={{ width: 500 }} value={record.ems_vrpreview_accessurl} />
            <Tooltip title="复制">
              <Button
                icon={<CopyOutlined />}
                onClick={() => {
                  handleCopy(record.ems_vrpreview_accessurl);
                }}
              />
            </Tooltip>
          </Input.Group>
        );
      },
    },
    {
      title: '创建时间',
      key: 'ems_vrpreview_createtime',
      dataIndex: 'ems_vrpreview_createtime',
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      key: 'ems_vrpreview_endtime',
      dataIndex: 'ems_vrpreview_endtime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key={`edit-${record.ems_vrpreview_id}`}
          onClick={(e) => {
            if (e && e.stopPropagation) {
              e.stopPropagation();
              shareEditRef?.current?.show(record);
            }
          }}
        >
          <Tooltip title="编辑">
            <EditOutlined />
          </Tooltip>
        </a>,
        <a key={`delete-${record.ems_vrpreview_id}`}>
          <Tooltip title="删除">
            <Popconfirm
              title="是否删除该项！"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                deleteVrPreview({
                  ids: [record.ems_vrpreview_id],
                }).then((res) => {
                  if (res.code === 200) {
                    message.success(res.message);
                  }
                  actionRef?.current?.reload();
                });
              }}
            >
              <DeleteOutlined />
            </Popconfirm>
          </Tooltip>
        </a>,
      ],
    },
  ];

  const request = async (
    // 第一个参数 params 查询表单和 params 参数的结合,表单搜索项会从 params 传入，
    // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
    params: any & {
      pageSize: number;
      current: number;
    },
    sort,
    filter,
  ) => {
    //const hide = message.loading('正在查询');
    try {
      // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
      // 如果需要转化参数可以在这里进行修改
      const queryParams = {
        ems_vrpreview_instanceid: instanceId,
        ...params,
        pageNum: params.current,
        ...sort,
        ...filter,
      };

      const response = await findByVrPreviewMap(queryParams);

      const list = {
        data: response?.result?.list,
        // success 请返回 true，
        // 不然 table 会停止解析数据，即使有数据
        success: response.code === 200 ? true : false,
        /** 列表的内容总数 */
        total: response?.result?.total,
      };

      return list;
    } catch (error) {
      return false;
    }
  };

  const leftCardLables: any = [
    {
      id: 0,
      name: '限时分享',
      icon: <FieldTimeOutlined style={{ color: '#ae81ff', fontSize: 24 }} />,
    },
  ];

  return (
    <>
      <Typography>
        <Paragraph></Paragraph>
      </Typography>
      <ProCard.Group title={false} extra={false} split="vertical">
        {/* 左侧模块 */}
        <ProCard colSpan="15%">
          <div className={styles.leftCardList}>
            <List
              rowKey="id"
              loading={false}
              dataSource={leftCardLables}
              renderItem={(item: any) => {
                return (
                  <List.Item key={item.id} onClick={() => setCurrentId(item.id)}>
                    <Card
                      hoverable
                      className={`${styles.card} ${
                        currentId == item.id ? styles.checkedCard : styles.card
                      }`}
                    >
                      <Card.Meta
                        title={
                          <Space>
                            <Avatar
                              shape="square"
                              size="large"
                              style={{ background: 'none' }}
                              icon={item.icon}
                            />
                            <Text ellipsis={{ tooltip: item.name }}>{item.name}</Text>
                          </Space>
                        }
                      />
                    </Card>
                  </List.Item>
                );
              }}
            />
          </div>
        </ProCard>
        {/* 右侧模块 */}
        <ProCard
          title={
            <Space style={{ marginLeft: 30 }}>
              链接有效期：{' '}
              <DatePicker showTime onChange={onChange} onOk={onOk} format={'YYYY/MM/DD HH:mm:ss'} />
              <Button type="primary" onClick={produceUrl} disabled={!endTime ? true : false}>
                生成链接
              </Button>
            </Space>
          }
        >
          <ProTable
            request={request}
            actionRef={actionRef}
            size="large"
            options={{ fullScreen: false, reload: false, setting: false, density: false }}
            rowKey="ems_vrpreview_id"
            search={false}
            defaultSize="middle"
            columns={columns}
            rowSelection={{
              selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              defaultSelectedRowKeys: [],
              onChange: (_, selectedRows) => {
                setSelectedRowKeys(selectedRows);
              },
            }}
            tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
              <Space size={24}>
                <span>
                  已选 {selectedRowKeys.length} 项
                  <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            )}
            tableAlertOptionRender={() => {
              return (
                <Space size={16}>
                  <Popconfirm
                    title="是否删除!"
                    okText="是"
                    cancelText="否"
                    onConfirm={() => {
                      const ids = selectedRowKeys?.map((item) => {
                        return item.ems_vrpreview_id;
                      });
                      deleteVrPreview({
                        ids: ids,
                      }).then((res) => {
                        if (res.code === 200) {
                          message.success(res.message);
                          setSelectedRowKeys([]);
                        }
                        actionRef?.current?.reload();
                      });
                    }}
                  >
                    <a>批量删除</a>
                  </Popconfirm>
                </Space>
              );
            }}
            pagination={{
              pageSize: 10,
            }}
          />
        </ProCard>
      </ProCard.Group>
      <AddOrEditShareUrl
        ref={shareEditRef}
        refreshList={() => {
          actionRef.current.reload();
        }}
      />
    </>
  );
};
export default ShareConfig;
